package electricity.controller.UserManageController;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import electricity.domain.Permission;
import electricity.domain.Role;
import electricity.domain.SysUser;
import electricity.dto.*;
import electricity.mapper.RolePermissionMapper;
import electricity.mapper.SysUserMapper;
import electricity.mapper.UserRoleMapper;
import electricity.result.Result;
import electricity.service.PermissionService;
import electricity.service.UserManageService;
import electricity.vo.*;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/usermanage")
@Tag(name="用户管理接口")
@Slf4j
public class UserManageController {
    @Autowired
    private UserManageService userManageService;
    @Autowired
    private PermissionService permissionService;

    @GetMapping("/list")
    @Operation(summary = "用户分页查询")
    public Result<PageResult>page(UserManageQueryDto userManageQueryDto) {
        log.info("用户分页查询:{}", userManageQueryDto);

        // 查询用户列表
        PageResult pageResult = userManageService.pageQuery(userManageQueryDto);

        return Result.success(pageResult);
    }
    @GetMapping("/rolelist")
    @Operation(summary = "角色列表")
    public Result<PageResult> rolelist(RoleQueryDto roleQueryDto) {
        log.info("角色列表:{}", roleQueryDto);

        // 角色列表
        PageResult pageResult = userManageService.pageQuery(roleQueryDto);

        return Result.success(pageResult);
    }
    @GetMapping("/role")
    @Operation(summary = "获取角色")
    public Result<List> role() {
        log.info("获取角色:{}");

        // 获取角色
        List<RoleVO> role = userManageService.getRole();

        return Result.success(role);
    }
    @GetMapping("/search")
    @Operation(summary = "用户查询")
    public Result<String> userSearch(@RequestBody SysUser sysUser)
    {
        log.info("用户查询：{}", sysUser);
        String token =userManageService.userSearch(sysUser);
        return Result.success(token);
    }

    @PostMapping("/addorupdate")
    @Operation(summary = "用户新增或更新")
    public Result<UserManageVO> addOrUpdate(@RequestBody UserUpdateDto dto) {
        if (dto.getId() != null) {
            // 有ID则更新
            UserManageVO vo = userManageService.update(dto);
            return Result.success(vo);
        } else {
            // 无ID则新增
            UserManageVO vo = userManageService.insert(dto);
            return Result.success(vo);
        }
    }


    @DeleteMapping("/delete/{id}")
    @Operation(summary = "用户删除")
    public Result<String> userDelete(@PathVariable Integer id){
        try {
            userManageService.userDelete(id);
            return Result.success("用户删除成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error("删除用户失败", e);
            return Result.error("系统错误，删除失败");
        }
    }
    @PostMapping("/batch_delete")
    @Operation(summary = "批量删除")
    public Result<String> batchDelete(@RequestBody List<Integer> ids) {
        try {
            userManageService.batchDelete(ids);
            return Result.success("批量删除成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    /**
     * 新增角色
     */
    @PostMapping("/addrole")
    @Operation(summary = "新增角色")
    public Result<String> addRole(@RequestBody Role role) {
        log.info("新增角色：{}", role);
        permissionService.addRole(role);
        return Result.success("角色新增成功");
    }

    /**
     * 更新角色
     */
    @PostMapping("/updaterole")
    @Operation(summary = "更新角色")
    public Result<String> updateRole(@RequestBody Role role) {
        log.info("更新角色：{}", role);
        permissionService.updateRole(role);
        return Result.success("角色更新成功");
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/deleterole/{id}")
    @Operation(summary = "删除角色")
    public Result<String> deleteRole(@PathVariable Integer id) {
        log.info("删除角色，ID：{}", id);
        permissionService.deleteRole(id);
        return Result.success("角色删除成功");
    }

    /**
     * 获取所有权限（4个顶级权限）
     */
    @GetMapping("/permissions/all")
    @Operation(summary = "获取所有权限")
    public Result<List<Permission>> getAllPermissions() {
        List<Permission> permissions = permissionService.getAllPermissions();
        return Result.success(permissions);
    }

    /**
     * 获取角色拥有的权限ID
     */
    @GetMapping("/{roleId}/permissions")
    @Operation(summary = "获取角色权限")
    public Result<List<Integer>> getRolePermissions(@PathVariable Integer roleId) {
        log.info("获取角色权限，角色ID：{}", roleId);
        List<Integer> permissionIds = permissionService.getRolePermissionIds(roleId);
        return Result.success(permissionIds);
    }

    /**
     * 保存角色权限
     */
    @PostMapping("/{roleId}/permissions")
    @Operation(summary = "保存角色权限")
    public Result<String> saveRolePermissions(
            @PathVariable Integer roleId,
            @RequestBody List<Integer> permissionIds) {
        log.info("保存角色权限，角色ID：{}，权限ID：{}", roleId, permissionIds);
        permissionService.saveRolePermissions(roleId, permissionIds);
        return Result.success("权限配置成功");
    }
}
